﻿using Dapper;
using Inventorycount.API.Read.Application.Command;
using Inventorycount.Dto;
using Inventorycount.ErrorCode;
using MediatR;
using System.Data;
using System.Threading;
using System.Threading.Tasks;

namespace Inventorycount.API.Read.Application.CommandHandLer
{
    public class GetoutboundCommandHandLer : IRequestHandler<GetoutboundCommand, APIResult<List<outboundDto>>>
    {
        private readonly IDbConnection repository;

        public GetoutboundCommandHandLer(IDbConnection repository)
        {
            this.repository = repository;
        }

        public async Task<APIResult<List<outboundDto>>> Handle(GetoutboundCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<outboundDto>>
            {
                Code = ResultCode.Ok,
                Message = "查询成功"
            };

            try
            {
                // 构建SQL查询语句
                var sql = @"
                    SELECT 
                        o.Id,
                        o.Outbound_code,
                        o.Transfer_id,
                        o.Warehouse_id,
                        o.Status,
                        o.Operator_id,
                        o.Operate_time,
                        o.Remark,
                        d.Id AS DetailId,  -- 分割点
                        d.Transfer_id,
                        d.Outbound_id,
                        d.Operator_id,
                        d.Goods_id,
                        d.Quantity,
                        d.Price,
                        d.Status AS DetailStatus,
                        d.Create_time,
                        d.Remark AS DetailRemark
                    FROM Wms_outbound_order o
                    JOIN Wms_outbound_detail d ON o.Id = d.Outbound_id
                    WHERE o.IsDeleted = 0";

                if (request.Transfer_id.HasValue)
                {
                    sql += " AND o.Transfer_id = @Transfer_id";
                }

                // 使用Dapper的多映射功能
                var outboundDictionary = new Dictionary<int, outboundDto>();
                var parameters = new { Transfer_id = request.Transfer_id };
                await repository.QueryAsync<outboundDto, OutbounddetailDto, outboundDto>(
                    sql,
                    (outbound, detail) =>
                    {
                        if (!outboundDictionary.TryGetValue(outbound.Id, out var outboundEntry))
                        {
                            outboundEntry = outbound;
                            outboundEntry.Detail = new List<OutbounddetailDto>();
                            outboundDictionary.Add(outbound.Id, outboundEntry);
                        }

                        if (detail != null)
                        {
                            outboundEntry.Detail.Add(detail);
                        }
                        return outboundEntry;
                    },
                    parameters,
                    splitOn: "DetailId");

                result.Data = outboundDictionary.Values.ToList();
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
}